#include <stdarg.h>
#include <windows.h>
#include "EngineLog.h"

EngineLog::EngineLog(void)
{
}

EngineLog& EngineLog::Get()
{
   static EngineLog log;
   return log;
}

bool EngineLog::Init()
{
   appLog.open("applog.txt");
   if (appLog.fail()) return false;
   clientLog.open("clntlog.txt");
   if (clientLog.fail()) return false;
   serverLog.open("srvrlog.txt");
   if (serverLog.fail()) return false;
   //user errors get logged to client

   //load the strings file
   if(!LoadStrings())return false;

   return true;
}

void EngineLog::Write(int target, const char *msg, ...)
{
   va_list args; va_start(args,msg);
   char* szBuf;
   int szBufLen = _vscprintf(msg, args);
   szBuf = (char*)malloc((szBufLen + 1) * sizeof(char));
   vsprintf_s(szBuf, szBufLen + 1, msg, args);

   if(target&LOG_APP)
   {
      appLog<<szBuf<<"\n";
      appLog.flush();
   }
   if(target&LOG_CLIENT)
   {
      clientLog<<szBuf<<"\n";
      clientLog.flush();
   }
   if(target&LOG_SERVER)
   {
      serverLog<<szBuf<<"\n";
      serverLog.flush();
   }
   if(target&LOG_USER)
   {
	  MessageBoxA(NULL,szBuf,"Message",MB_OK);
   }
   if (target&LOG_DEBUG)
   {
	   OutputDebugStringA(szBuf);
   }

   free(szBuf);
}

void EngineLog::Write(int target, unsigned long msgID, ...)
{
   va_list args; va_start(args, msgID);
   char szBuf[1024];
   vsprintf_s(szBuf,1024,logStrings[msgID].c_str(),args);
   Write(target,szBuf);
}

//under Win32, the strings get read in from a string table resource
bool EngineLog::LoadStrings()
{
   for(unsigned long i=0;i<MAX_LOG_STRINGS;i++)
   {
      char szBuf[1024];
      if(!LoadStringA(GetModuleHandleA("engine"),i,szBuf,1024))
         break; //returning 0 means no more strings
      logStrings[i]=szBuf;
   }
   return true;
}


